package com.kygeng.springframework.beans.factory.support;

import com.kygeng.springframework.beans.BeansException;
import com.kygeng.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Title: SimpleInstantiationStrategy
 * @Author: kygeng
 * @Package: com.kygeng.springframework.beans.factory.support
 * @Date: 2024/7/21 16:52
 * @Description: JDK实例化
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        Class clazz = beanDefinition.getBeanClass();
        try {
            if (null != clazz) {
                // 有构造函数的实例化
                // getDeclaredConstructor(Class<?>... parameterTypes) 把入参信息传递给 newInstance 进行实例化
                return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            } else {
                //无构造函数实例化
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            throw new BeansException("Failed to instantiate " + beanName, e);
        }
    }
}
